package uno.linze.wallpaper.domain.identity.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import uno.linze.wallpaper.domain.identity.entity.UserProfiles;
import uno.linze.wallpaper.domain.identity.entity.UserRoles;
import uno.linze.wallpaper.domain.identity.entity.Users;
import uno.linze.wallpaper.domain.identity.mapper.UserProfilesMapper;
import uno.linze.wallpaper.domain.identity.mapper.UserRolesMapper;
import uno.linze.wallpaper.domain.identity.mapper.UsersMapper;
import uno.linze.wallpaper.domain.identity.repository.UserResponsitory;

@Repository
public class UserResponsitoryImpl implements UserResponsitory {
    private static final Logger logger = LoggerFactory.getLogger(UserResponsitoryImpl.class);

    private final UsersMapper usersMapper;
    private final UserRolesMapper userRolesMapper;
    private final UserProfilesMapper userProfilesMapper;

    public UserResponsitoryImpl(UsersMapper usersMapper, UserRolesMapper userRolesMapper, UserProfilesMapper userProfilesMapper) {
        this.usersMapper = usersMapper;
        this.userRolesMapper = userRolesMapper;
        this.userProfilesMapper = userProfilesMapper;
    }


    /**
     * 注册用户，包含事务管理和错误日志记录
     * @param username 用户名
     * @param email 邮箱
     * @param passwordHash 加密后的密码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String username, String email, String passwordHash) {
        try {
            logger.info("开始为用户注册, email: {}", email);

            // 1. 插入用户基本信息
            Users user = new Users();
            user.setEmail(email);
            user.setPasswordHash(passwordHash);
            usersMapper.insert(user);
            logger.debug("创建用户成功, userId: {}", user.getId());

            // 2. 分配用户角色
            UserRoles userRoles = new UserRoles();
            userRoles.setUserId(user.getId());
            userRoles.setRoleId(5); // 默认角色ID
            userRolesMapper.insert(userRoles);
            logger.debug("为用户分配角色成功, userId: {}, roleId: 5", user.getId());

            // 3. 创建用户资料
            UserProfiles userProfiles = new UserProfiles();
            userProfiles.setUserId(user.getId());
            userProfiles.setUsername(username);
            userProfilesMapper.insert(userProfiles);
            logger.debug("创建用户资料成功, userId: {}", user.getId());

            logger.info("用户注册成功, email: {}", email);
        } catch (Exception e) {
            logger.error("用户注册失败, email: {}. 错误信息: {}", email, e.getMessage(), e);
            // 向上抛出异常，触发事务回滚
            throw new RuntimeException("用户注册失败", e);
        }
    }

    /**
     * 根据用户名查找用户，用于登录验证
     * @param username 用户名
     * @param password 密码（此处未使用，验证在服务层进行）
     * @return 如果找到则返回Users对象，否则返回null
     */
    @Override
    public Users login(String username, String password) {
        try {
            logger.debug("尝试通过用户名查找用户: {}", username);
            // 1. 根据 username 查找 UserProfiles
            QueryWrapper<UserProfiles> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            UserProfiles userProfile = userProfilesMapper.selectOne(queryWrapper);

            if (userProfile == null) {
                logger.warn("未找到用户名为 '{}' 的用户资料", username);
                return null;
            }

            // 2. 根据 userId 查找 Users
            Users user = usersMapper.selectById(userProfile.getUserId());
            if (user == null) {
                logger.error("数据不一致：找到了用户资料，但未找到对应的用户核心信息。userId: {}", userProfile.getUserId());
                return null;
            }

            logger.debug("成功找到用户: {}", username);
            return user;
        } catch (Exception e) {
            logger.error("通过用户名查找用户时出错: {}. 错误: {}", username, e.getMessage(), e);
            throw new RuntimeException("查找用户失败", e);
        }
    }
}